﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Lookstone.Utility
{
	public static class XmlTool
	{
		/// <summary>
		/// Retrieves an attribute from an XmlNode. If the attribute doesn't exist, it creates it and associates it with the XmlNode.
		/// </summary>
		/// <param name="doc">XmlDocument that will contain the attribute</param>
		/// <param name="node">Node that contains / will contain the attribute</param>
		/// <param name="preceedingAttribute">(optional) Reference to the attribute that this attribute should be inserted after, if it does not exist</param>
		/// <param name="attributeName">Name of the attribute to be inserted / retrieved</param>
		/// <returns>Reference to the attribute</returns>
		public static XmlAttribute GetOrCreateAttribute(XmlDocument doc, XmlNode node, XmlAttribute preceedingAttribute, string attributeName)
		{
			XmlAttribute attr = node.Attributes[attributeName];

			if (attr == null)
			{
				attr = doc.CreateAttribute(attributeName);

				if (preceedingAttribute != null)
					node.Attributes.InsertAfter(attr, preceedingAttribute);
				else
					node.Attributes.Append(attr);
			}

			return attr;
		}

		/// <summary>
		/// Gets the value of an attribute on the node.
		/// </summary>
		/// <param name="node">Node containing the attribute</param>
		/// <param name="attributeName">The attribute to retrieve</param>
		/// <returns>The value contained in the attribute, or string.Empty if the attribute doesn't exist</returns>
		public static string GetAttributeValue(XmlNode node, string attributeName)
		{
			if (node != null && node.Attributes[attributeName] != null)
				return node.Attributes[attributeName].Value;

			return string.Empty;
		}

		/// <summary>
		/// Sets the value of an attribute on the node
		/// </summary>
		/// <param name="node">Node containing or to contain the attribute</param>
		/// <param name="attributeName">Name of the attribute</param>
		/// <param name="attributeValue">New value for the attribute</param>
		public static void SetAttributeValue(XmlNode node, string attributeName, string attributeValue)
		{
			XmlAttribute attr = GetOrCreateAttribute(node.OwnerDocument, node, null, attributeName);

			attr.Value = attributeValue;
		}

		/// <summary>
		/// Removes an attribute from an XmlNode object
		/// </summary>
		/// <param name="node">Node to remove the attribute from</param>
		/// <param name="attributeName">Name of the attribute to remove</param>
		public static void RemoveAttribute(XmlNode node, string attributeName)
		{
			XmlAttribute attr = node.Attributes[attributeName];

			if (attr != null)
				node.Attributes.Remove(attr);
		}
	}
}
